package com.example.captchademo.demos.web;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("/admin")
@RestController
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private  static  final  long TIME_OUT=60*1000;
    public  boolean check(String inputCaptcha, HttpSession session) {
        //判断输入的验证码是否为空
        //获取生成的验证码
        //对比，生成的验证码和输入的验证码是否一致
        //确认验证码是否过期
        if(!StringUtils.hasLength(inputCaptcha)) {
            return false;
        }
       //生成正确的验证码
        String saveCaptcha=(String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveCaptchaDate=(Date)session.getAttribute(KAPTCHA_SESSION_DATE);
        if(inputCaptcha.equalsIgnoreCase(saveCaptcha)) {//不区分大小写
            if(saveCaptchaDate!=null||System.currentTimeMillis()-saveCaptchaDate.getTime()<TIME_OUT) {
                return true;
            }
        }
        return false;

    }
}
